package com.mama100.rpc.mdp.job;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.annotation.Resource;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.mama100.mc.client.MCConsumer;
import com.mama100.mc.client.MCTarget;
import com.mama100.mc.client.utils.MCConfig;
import com.mama100.rpc.mdp.MdpInoutUtil;
import com.mama100.rpc.mdp.service.finagle.CustTerminalBelongService;
import com.mama100.rpc.mdp.spring.RunTimeBean;
import com.mama100.rpc.mdp.thrift.inout.GetTCustBelongTerminalRequest;
import com.mama100.rpc.mdp.thrift.inout.common.BaseResponse;
import com.sun.messaging.jmq.jmsclient.MapMessageImpl;

/**
 * 说明：实现会员归属门店job
 * 依赖数据库: crmJdbcTemplate<br>
 * 表: mdp_so_cust_terminal<br>
 * 序列:MDP_SO_CUST_TERMINAL_SEQ,<br>
 * 
 * @author 7880
 */
@Service("CustomerBelongTerminalJob")
public class CustomerBelongTerminalJob {

	protected Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Resource(name = "custTerminalBelongService")
	private CustTerminalBelongService custTerminalBelongService;
	
	@Resource(name = "runTimeBean")
	private RunTimeBean runTimeBean;
	
	@Resource(name = "crmJdbcTemplate")
	JdbcTemplate jdbcTemplate;
	
	/**
	 * 工作线程 监听队列 "TX_PRODUCT_POINT_DETAILS." + yyyymmdd<br>
	 *
	 */
	class WorkThread extends Thread {
		
		@Override
		public void run() {
			
			//获取唯一ID
			String serverId="mdpStepTouch-server-";
			try{
				//获取服务器IP
				String ip = InetAddress.getLocalHost().getHostAddress();
				ip = ip.replaceAll("\\.", "-");
				serverId += ip;
				} catch (UnknownHostException e1) {
					e1.printStackTrace();
			}
			//获取进程pid
			/*String pidName = ManagementFactory.getRuntimeMXBean().getName(); 
			pidName = pidName.replaceAll("\\.", "-");
			serverId += pidName;*/
			
			//获取服务端地址
			String serverAddress = "";
			if(runTimeBean != null && "dev".equals(runTimeBean.getEnv())){
				serverAddress = MCConfig.ZK_SERVER_DEV;
			}else if(runTimeBean != null && "prd".equals(runTimeBean.getEnv())){
				serverAddress = MCConfig.ZK_SERVER_PRD;
			}
			
			MCConsumer mc = new MCConsumer(serverAddress,serverId, MCTarget.MDP_STEP_TOUCH, true);
			
			try {
				mc.setMessageListener(new MessageListener() {
					@Override
					public void onMessage(Message message) {
						
						String seqNo = "";  //流水号
						String reqValue = "";//传参信息
						BaseResponse response = null; //调接口返回
						String msg = "";
						
						try {
							MapMessageImpl mapMessageImpl = (MapMessageImpl)message;
							
							seqNo = mapMessageImpl.getString("seqNo");
							String msgType = mapMessageImpl.getString("msgType");
							reqValue += "msgType："+msgType;
							
							//会员归属门店接口：customerBelongTerminal
							if("CBT".equals(msgType)){
								try {
									//获取值
									long customerId = mapMessageImpl.getLong("customerId");
									reqValue += "，customerId："+customerId;
									
									String terminalCode = mapMessageImpl.getString("terminalCode");
									reqValue += "，terminalCode："+terminalCode;
									
									int fromType = mapMessageImpl.getInt("fromType");
									reqValue += "，fromType："+fromType;
									
									String orderId = "NOORDERID";
									try {
										orderId = mapMessageImpl.getString("orderId");
										reqValue += "，orderId："+orderId;
									} catch (Exception e) {
									}
									
									
									String fromSystem = mapMessageImpl.getString("fromSystem");
									reqValue += "，fromSystem："+fromSystem;
									
									//会员不能为空
									if(customerId > 0 && terminalCode != null && !"".equals(terminalCode)){
										//创建传参实例
										GetTCustBelongTerminalRequest req = MdpInoutUtil.getGetTCustBelongTerminalRequest(seqNo); 
										req.setCustomerId(customerId);     /*会员id*/
										req.setTerminalCode(terminalCode); /*门店编码*/
										req.setFromType(fromType);         /*来源类型入口 1会员领卡 2会员最喜欢门店 3会员邀请码 4会员交易完成*/
										req.setOrderId(orderId);           /*订单ID*/
										req.setFromSystem(fromSystem);     /*来源系统*/
										
										//调度方法
										response = custTerminalBelongService.customerBelongTerminal(req).get();
									}else{
										msg = "会员与门店不能为空";
									}
								} catch (Exception e) {
									e.printStackTrace();
									msg = "获取会员归属门店接口数据出错。";
								}
								
							}
						} catch (Exception e) {
							e.printStackTrace();
							msg = "获取流水号与消息类型数据出错。";
						}
						//记录日志
						logDb(seqNo, reqValue, response,msg);
					}
				});
				//建立连接
				mc.open();
			} catch (Exception e) {
				e.printStackTrace();
				log.error("开始订阅消息队列mdpStepTouch出错");
			}
		}	
	}
	
	//启动线程
	public void startWorkThread() {
		try {
			new WorkThread().start();
		} catch (Exception e) {
			log.error("启动消息队列监听线程出错。");
		}
		
	}
	
	/**
	 * 日志处理
	 */
	private void logDb(String seqNo, String reqValue, BaseResponse response,String msg) {
		if(response != null){
			if("201".equals(response.getRespCode())){
				log.error("customerBelongTerminal-->>seqNo:"+seqNo+"--reqValue:"+reqValue+"--respCode:"+response.getRespCode()+"--respDesc"+response.getRespDesc());
				try {
					//String sql = "insert into MDP_SO_CUST_BEONG_TERMINAL_LOG(ID,seqNo,reqValue,respCode,respDesc,msg) values(MDP_SO_CUST_TERMINAL_SEQ.nextval,?,?,?,?,?)";
					//jdbcTemplate.update(sql, seqNo, reqValue, response.getRespCode(),response.getRespDesc(),msg);
				} catch (DataAccessException e) {
					log.error("insert send record error", e);
				}
			}else{
				log.info("customerBelongTerminal-->>seqNo:"+seqNo+"--reqValue:"+reqValue+"--respCode:"+response.getRespCode()+"--respDesc"+response.getRespDesc());
			}
			
		}else{
			log.error("customerBelongTerminal-->>seqNo:"+seqNo+"--reqValue:"+reqValue+"--msg"+msg);
			try {
				//String sql = "insert into MDP_SO_CUST_BEONG_TERMINAL_LOG(ID,seqNo,reqValue,respCode,respDesc,msg) values(MDP_SO_CUST_TERMINAL_SEQ.nextval,?,?,?,?,?)";
				//jdbcTemplate.update(sql, seqNo, reqValue, null,null,msg);
			} catch (DataAccessException e) {
				log.error("insert send record error", e);
			}
		}
		
	}
}
